<template>
  <div class="create-order-page">
    <nut-form ref="formRef" :model-value="formData" :rules="rules">
      <!-- 产品选择 -->
      <nut-cell-group title="产品选择">
        <nut-popup v-model:visible="showProductPicker" position="bottom">
          <nut-picker
            v-model="selectedProductIndex"
            :columns="productColumns"
            title="选择产品"
            @confirm="onProductConfirm"
            @cancel="showProductPicker = false"
          />
        </nut-popup>
        <nut-form-item label="产品" required prop="productId" :rules="[{ required: true, message: '请选择产品' }]">
          <nut-cell :title="selectedProductName || '请选择产品'" is-link @click="showProductPicker = true" />
        </nut-form-item>
      </nut-cell-group>

      <!-- 客户信息 -->
      <nut-cell-group title="客户信息">
        <!-- 证件相关放在最上面，优先识别再回填其他信息 -->
        <nut-form-item label="证件类型" prop="idType">
          <nut-radio-group v-model="formData.idType" direction="horizontal">
            <nut-radio v-for="item in idTypeOptions" :key="item.dictValue || ''" :label="item.dictValue || ''">
              {{ item.dictLabel }}
            </nut-radio>
          </nut-radio-group>
        </nut-form-item>

        <nut-form-item label="证件号" prop="customIdCard">
          <div class="id-card-input">
            <nut-input v-model="formData.customIdCard" placeholder="请输入证件号" clearable />
            <nut-button size="small" type="primary" @click="handleOcr('idCard')"> 证件识别 </nut-button>
          </div>
        </nut-form-item>

        <nut-form-item label="客户姓名" required prop="customName" :rules="[{ required: true, message: '请输入客户姓名' }]">
          <nut-input v-model="formData.customName" placeholder="请输入客户姓名" clearable />
        </nut-form-item>

        <nut-form-item label="客户手机号" required prop="customPhone" :rules="phoneRules">
          <nut-input v-model="formData.customPhone" placeholder="请输入客户手机号" type="tel" clearable />
        </nut-form-item>
      </nut-cell-group>

      <!-- OCR识别区域 -->
      <nut-popup v-model:visible="showOcrModal" position="center" round :style="{ padding: '24px', width: '90%' }">
        <div class="ocr-modal">
          <h3 class="modal-title">{{ ocrModalTitle }}</h3>
          <div class="ocr-upload">
            <input ref="ocrFileInputRef" type="file" accept="image/*" style="display: none" @change="handleOcrFileChange" />
            <nut-button type="primary" block @click="triggerOcrFileInput">上传图片</nut-button>
            <div v-if="ocrImageUrl" class="ocr-preview">
              <img :src="ocrImageUrl" alt="OCR预览" />
            </div>
          </div>
          <div class="modal-actions">
            <nut-button plain type="default" @click="showOcrModal = false">取消</nut-button>
            <nut-button type="primary" :loading="ocrLoading" @click="confirmOcr">识别</nut-button>
          </div>
        </div>
      </nut-popup>

      <!-- 支付信息 -->
      <nut-cell-group title="支付信息">
        <nut-form-item label="支付渠道" required prop="payChannel" :rules="[{ required: true, message: '请选择支付渠道' }]">
          <nut-radio-group v-model="formData.payChannel" direction="horizontal">
            <nut-radio v-for="item in payChannelOptions" :key="item.dictValue || ''" :label="item.dictValue || ''">
              {{ item.dictLabel }}
            </nut-radio>
          </nut-radio-group>
        </nut-form-item>

        <!-- 线下支付才选择具体支付方式 -->
        <nut-form-item v-if="formData.payChannel === '01'" label="支付方式" prop="payMethod">
          <nut-radio-group v-model="formData.payMethod" direction="horizontal">
            <nut-radio v-for="item in payMethodOfflineOptions" :key="item.dictValue || ''" :label="item.dictValue || ''">
              {{ item.dictLabel }}
            </nut-radio>
          </nut-radio-group>
        </nut-form-item>

        <nut-form-item label="支付类型" required prop="payType" :rules="[{ required: true, message: '请选择支付类型' }]">
          <nut-radio-group v-model="formData.payType" direction="horizontal">
            <nut-radio v-for="item in payTypeOptions" :key="item.dictValue || ''" :label="item.dictValue || ''">
              {{ item.dictLabel }}
            </nut-radio>
          </nut-radio-group>
        </nut-form-item>

        <nut-form-item label="订单总金额" required prop="totalAmount" :rules="amountRules">
          <nut-input v-model="formData.totalAmount" placeholder="请输入订单总金额" type="number" clearable />
        </nut-form-item>

        <nut-form-item v-if="formData.payType === '01'" label="定金" prop="depositAmount" :rules="amountRules">
          <nut-input v-model="formData.depositAmount" placeholder="请输入定金" type="number" clearable />
        </nut-form-item>
      </nut-cell-group>

      <!-- 提交按钮 -->
      <div class="submit-btn-wrap">
        <nut-button type="primary" block :loading="submitting" @click="handleSubmit">创建订单</nut-button>
      </div>
    </nut-form>

    <!-- 线上支付二维码弹窗 -->
    <nut-popup v-model:visible="qrVisible" position="center" round :style="{ width: '80%', padding: '24px' }">
      <div class="pay-qr-modal">
        <h3 class="modal-title">扫码支付</h3>
        <div class="pay-info">
          <div>流水号：{{ qrPayInfo?.payNo || '--' }}</div>
          <div>支付金额：¥{{ (qrPayInfo?.totalAmount || Number(formData.totalAmount)).toFixed(2) }}</div>
        </div>
        <div class="qr-wrapper">
          <img v-if="qrPayInfo?.qrCodeUrl" :src="qrPayInfo?.qrCodeUrl" alt="支付二维码" />
          <div v-else class="qr-placeholder">
            暂未获取到二维码，请确认后端返回字段 <span>qrCodeUrl</span> 已对接
          </div>
        </div>
        <p class="pay-tip">请使用微信或支付宝扫码完成支付</p>
        <nut-button type="primary" block @click="goToOrderCenter">我已完成支付</nut-button>
      </div>
    </nut-popup>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { showToast } from '@nutui/nutui';
  import { useEnumStore } from '@/store/modules/enum';
  import {
    fetchProductSelect,
    createOrder,
    fetchPayInfo,
    idCardOcr,
    drivingLicenseOcr,
    type ProductInfo,
    type CreateOrderPayload,
    type OrderPayInfo,
  } from '@/api/order';
  import { uploadFile } from '@/api';

  const router = useRouter();
  const enumStore = useEnumStore();

  const formRef = ref<any>(null);
  const submitting = ref(false);

  // 表单数据
  const formData = reactive<CreateOrderPayload>({
    productId: '',
    payChannel: '00',
    payMethod: '00',
    payType: '00',
    totalAmount: 0,
    depositAmount: 0,
    idType: '00',
    customName: '',
    customIdCard: '',
    customPhone: '',
  });

  // 线上支付二维码弹窗
  const qrVisible = ref(false);
  const qrPayInfo = ref<OrderPayInfo | null>(null);

  // 表单验证规则
  const phoneRules = [
    { required: true, message: '请输入客户手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
  ];

  const amountRules = [
    { required: true, message: '请输入金额' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额' },
    {
      validator: (value: string | number) => {
        const num = Number(value);
        if (Number.isNaN(num)) return false;
        const product = productList.value.find((item) => item.productId === formData.productId);
        if (!product || !product.productPriceStart) return true;
        const min = Number(product.productPriceStart);
        if (Number.isNaN(min)) return true;
        return num >= min;
      },
      message: '金额不能低于产品最低金额',
    },
  ];

  const rules = {
    customName: [{ required: true, message: '请输入客户姓名' }],
    customPhone: phoneRules,
    productId: [{ required: true, message: '请选择产品' }],
    payChannel: [{ required: true, message: '请选择支付渠道' }],
    payType: [{ required: true, message: '请选择支付类型' }],
    totalAmount: amountRules,
  };

  // 枚举选项
  const idTypeOptions = computed(() => enumStore.getEnumByType('id_type'));
  const payChannelOptions = computed(() => enumStore.getEnumByType('sp_order_pay_channel'));
  const payMethodOfflineOptions = computed(() => enumStore.getEnumByType('sp_order_offline_pay_method'));
  const payTypeOptions = computed(() => enumStore.getEnumByType('sp_order_pay_type'));

  // 产品选择
  const showProductPicker = ref(false);
  const productList = ref<ProductInfo[]>([]);
  const selectedProductName = ref('');
  const selectedProductIndex = ref<number[]>([0]);

  const productColumns = computed(() => {
    return [
      productList.value.map((item) => ({
        text: item.productName || '',
        value: item.productId || '',
      })),
    ];
  });

  // 获取产品列表
  const getProductList = async () => {
    try {
      const list = await fetchProductSelect();
      productList.value = list;
    } catch (error: any) {
      console.error('获取产品列表失败', error);
      showToast.text(error?.message || '获取产品列表失败');
    }
  };

  const onProductConfirm = ({ selectedOptions }: any) => {
    if (selectedOptions && selectedOptions.length > 0) {
      const productId = selectedOptions[0].value;
      const product = productList.value.find((item) => item.productId === productId);
      formData.productId = productId;
      selectedProductName.value = product?.productName || '';
      // 默认订单总金额取产品最高金额
      if (product?.productPriceEnd) {
        formData.totalAmount = Number(product.productPriceEnd) || 0;
      }
      // 同步更新索引
      const index = productList.value.findIndex((item) => item.productId === productId);
      selectedProductIndex.value = [index >= 0 ? index : 0];
      showProductPicker.value = false;
    }
  };

  // OCR识别
  const showOcrModal = ref(false);
  const ocrModalTitle = ref('');
  const ocrType = ref<'idCard' | 'drivingLicense' | 'vehicleLicense'>('idCard');
  const ocrFileInputRef = ref<HTMLInputElement | null>(null);
  const ocrImageUrl = ref('');
  const ocrLoading = ref(false);

  const handleOcr = (type: 'idCard' | 'drivingLicense' | 'vehicleLicense') => {
    ocrType.value = type;
    const titles: Record<string, string> = {
      idCard: '身份证识别',
      drivingLicense: '驾驶证识别',
      vehicleLicense: '行驶证识别',
    };
    ocrModalTitle.value = titles[type] || 'OCR识别';
    showOcrModal.value = true;
    ocrImageUrl.value = '';
  };

  const triggerOcrFileInput = () => {
    ocrFileInputRef.value?.click();
  };

  const handleOcrFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    if (!file) return;

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      showToast.text('请选择图片文件');
      return;
    }

    // 验证文件大小（限制 5MB）
    if (file.size > 5 * 1024 * 1024) {
      showToast.text('图片大小不能超过 5MB');
      return;
    }

    try {
      console.log('file>>>>>>>>', file);
      // 上传图片
      const result = await uploadFile(file);
      if (result?.url) {
        ocrImageUrl.value = result.url;
      } else {
        showToast.text('图片上传失败');
      }
    } catch (error: any) {
      console.error('图片上传失败', error);
      showToast.text(error?.message || '图片上传失败');
    }
  };

  const confirmOcr = async () => {
    if (!ocrImageUrl.value) {
      showToast.text('请先上传图片');
      return;
    }

    try {
      ocrLoading.value = true;
      let result;

      switch (ocrType.value) {
        case 'idCard':
          result = await idCardOcr(ocrImageUrl.value);
          if (result) {
            formData.customName = result.name || '';
            formData.customIdCard = result.idNumber || '';
            formData.idType = '00';
          }
          break;
        case 'drivingLicense':
          result = await drivingLicenseOcr(ocrImageUrl.value);
          if (result) {
            formData.customName = result.name || '';
            formData.customIdCard = result.licenseNumber || '';
            formData.idType = '01';
          }
          break;
      }

      showToast.text('识别成功');
      showOcrModal.value = false;
      ocrImageUrl.value = '';
    } catch (error: any) {
      console.error('OCR识别失败', error);
      showToast.text(error?.message || 'OCR识别失败');
    } finally {
      ocrLoading.value = false;
    }
  };

  const loadPayInfoForQr = async (payId: string) => {
    try {
      const { code, data, msg }: any = await fetchPayInfo(payId);
      if (code !== 200) {
        showToast.text(msg || '获取支付信息失败');
        return;
      }
      qrPayInfo.value = data as OrderPayInfo;
      qrVisible.value = true;
    } catch (error: any) {
      console.error('获取支付信息失败', error);
      showToast.text(error?.message || '获取支付信息失败');
    }
  };

  const goToOrderCenter = () => {
    qrVisible.value = false;
    router.push('/order');
  };

  // 提交表单
  const handleSubmit = () => {
    formRef.value?.validate().then(async ({ valid, errors }: any) => {
      if (!valid) {
        console.warn(errors);
        return;
      }

      try {
        submitting.value = true;

        const payload: CreateOrderPayload = {
          productId: formData.productId,
          payChannel: formData.payChannel,
          payType: formData.payType,
          totalAmount: Number(formData.totalAmount),
          customName: formData.customName,
          customPhone: formData.customPhone,
        };

        // 线下支付才传具体支付方式
        if (formData.payChannel === '01' && formData.payMethod) {
          payload.payMethod = formData.payMethod;
        }

        if (formData.payType === '01' && formData.depositAmount) {
          payload.depositAmount = Number(formData.depositAmount);
        }

        if (formData.idType) {
          payload.idType = formData.idType;
        }

        if (formData.customIdCard) {
          payload.customIdCard = formData.customIdCard;
        }

        const { code, data, msg }: any = await createOrder(payload);
        if (code !== 200) throw new Error(msg);
        showToast.text('创建订单成功');

        // 线上支付：弹出二维码，提示扫码支付
        if (formData.payChannel === '00' && data?.payId) {
          await loadPayInfoForQr(data.payId);
        } else {
          // 线下支付：直接跳转订单中心
          router.push('/order');
        }
      } catch (error: any) {
        console.error('创建订单失败', error);
        showToast.text(error?.message || '创建订单失败');
      } finally {
        submitting.value = false;
      }
    });
  };

  // 初始化
  getProductList();
</script>

<style lang="scss" scoped>
  .create-order-page {
    // min-height: 100vh;
    padding-bottom: 20px;
  }

  .id-card-input {
    display: flex;
    align-items: center;
    gap: 10px;

    .nut-input {
      flex: 1;
    }
  }

  .ocr-modal {
    .modal-title {
      margin: 0 0 20px;
      font-size: 32px;
      text-align: center;
    }

    .ocr-upload {
      margin-bottom: 20px;

      .ocr-preview {
        margin-top: 20px;
        text-align: center;

        img {
          max-width: 100%;
          max-height: 400px;
          border-radius: 8px;
        }
      }
    }

    .modal-actions {
      display: flex;
      justify-content: space-between;
      gap: 20px;

      .nut-button {
        flex: 1;
      }
    }
  }

  .submit-btn-wrap {
    padding: 20px;
    margin-top: 20px;
  }

  .pay-qr-modal {
    text-align: center;

    .modal-title {
      margin: 0 0 12px;
      font-size: 32px;
      font-weight: 600;
    }

    .pay-info {
      margin-bottom: 16px;
      font-size: 26px;
      color: #333;

      div + div {
        margin-top: 4px;
      }
    }

    .qr-wrapper {
      margin: 0 auto 12px;
      width: 200px;
      height: 200px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f7f7f7;
      border-radius: 8px;

      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }

      .qr-placeholder {
        padding: 8px;
        font-size: 22px;
        color: #999;

        span {
          color: #1989fa;
        }
      }
    }

    .pay-tip {
      margin: 0 0 16px;
      font-size: 24px;
      color: #666;
    }
  }
</style>
